//
//  ZYCTeaLeaveRecordApproveViewController.m
//  ZDSC
//
//  Created by 张威 on 2021/10/21.
//

#import "ZYCTeaLeaveRecordApproveViewController.h"
#import "ZYCTeaLeaveRecordApproveBottomView.h"
#import "ZYCTeaLeaveRecordDetailCell.h"
#import "ZYCTeaLeaveAddPhotoCell.h"
#import "ZYCTeaLeaveOptionalCell.h"
#import "ZYCManageCourseTeachTimeCell.h"
#import "ZYCTeaLeaveRecordDetailHeaderView.h"
#import "ZYCTeaLeaveApproveViewController.h"
#import "ZYCTeaLeaveRecordFlowChartView.h"
#import "ZYCTeaLeaveRecordRootModel.h"
#import "ZYCTeaLeaveFlowChartModel.h"
#import "ZYCTeaLeaveApproverViewController.h"


@interface ZYCTeaLeaveRecordApproveViewController ()<UITableViewDelegate,UITableViewDataSource,ZYCTeaLeaveRecordApproveBottomViewDelegate,ZYCTeaLeaveAddPhotoCellDelegate,ZYCTeaLeaveRecordFlowChartViewDelegate>
@property (nonatomic, strong) ZYCTeaLeaveRecordFlowChartView *flowChartView;
@property (nonatomic, strong) ZYCTeaLeaveRecordDetailHeaderView *headerView;
@property (nonatomic, strong) ZYCTeaLeaveRecordApproveBottomView *bottomView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) ZYCTeaLeaveRecordRootModel *detailModel;
@property (nonatomic, strong) NSMutableArray *toUsers;
@property (nonatomic, strong) NSMutableArray *approveArray;
@property (nonatomic, strong) NSArray *footerDataSource;
@property (nonatomic, assign) NSInteger nodeType;
@end

@implementation ZYCTeaLeaveRecordApproveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"请假审批";
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = self.flowChartView;
    
    [self loadTeaLeaveDetial];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 2) {
        return 3;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 3) {// 请假事由
        ZYCTeaLeaveOptionalCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCTeaLeaveOptionalCell class]) forIndexPath:indexPath];
        cell.isHid = YES;
        cell.titleString = self.dataSource[indexPath.section];
        NSString *leaveReason = nil;
        if (self.detailModel.leaveReason.length > 0) {
            leaveReason = self.detailModel.leaveReason;
        }else{
            leaveReason = @"无";
        }
        cell.contentString = leaveReason;
        return cell;
    }else if(indexPath.section == 4){// 上传图片 ** 显示图片
        ZYCTeaLeaveAddPhotoCell *cell = [ZYCTeaLeaveAddPhotoCell teacherLeaveAddPhotoCellWithType:ZYCTeaLeaveAddPhotoTypeShow TableView:tableView];
        cell.titleString = self.dataSource[indexPath.section];
        cell.dataSource = self.detailModel.files.mutableCopy;
        cell.delegate = self;
        return cell;
    }else if(indexPath.section == 2 && indexPath.row != 0){
        ZYCManageCourseTeachTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCManageCourseTeachTimeCell class]) forIndexPath:indexPath];
        if (indexPath.row == 1) {
            cell.contentString = self.detailModel.leaveStartTime;
        }else{
            cell.contentString = self.detailModel.leaveEndTime;
        }
        return cell;
    }else{
        ZYCTeaLeaveRecordDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCTeaLeaveRecordDetailCell class]) forIndexPath:indexPath];
        cell.titleLabel.text = self.dataSource[indexPath.section];
        switch (indexPath.section) {
            case 0:{// 所属部门
                cell.contentLabel.text = self.detailModel.deptName;
                break;
            }
            case 1:{// 所属岗位
                cell.contentLabel.text = self.detailModel.postName;
                break;
            }
            case 2:{// 类型/时间
                cell.contentLabel.text = [NSString stringWithFormat:@"%@/%@天",self.detailModel.leaveTypeName,self.detailModel.leaveDays];
                break;
            }
            default:
                break;
        }
        return cell;
    }
    
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5.0f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 3) {
        return 150.0f;
    }else if(indexPath.section == 4){
        return 150.0f;
    }
    return 55.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}


#pragma mark - ZYCTeaLeaveRecordFlowChartViewDelegate

// 选择审批人
- (void)teaLeaveRecordFlowChartViewAddApprover:(ZYCTeaLeaveFlowChartModel *)model{
    ZYCWeakSelf
    ZYCTeaLeaveApproverViewController *vc = [[ZYCTeaLeaveApproverViewController alloc] init];
    vc.model = model;
    NSMutableArray *temp = [NSMutableArray array];
    if (self.nodeType == 3) {
        vc.selectApproverBlock = ^(NSMutableArray<ZYCTeaLeaveApplyUserModel *> * _Nonnull appvoers) {
            for (ZYCTeaLeaveApplyUserModel *m in appvoers) {
                m.nodeType = @"3";
                [temp addObject:m.userId];
            }
            self.toUsers = temp.copy;
            for (ZYCTeaLeaveFlowChartModel *model in self.footerDataSource) {
                if ([model.nodeType  integerValue] == 3) { // 下一审批节点
                    model.applyUserList = appvoers;
                }
            }
            weakSelf.flowChartView.dataSource = weakSelf.footerDataSource;
            [weakSelf.flowChartView reload];
        };
    }else{
        self.toUsers = @[].mutableCopy;
    }
    [self.navigationController pushViewController:vc animated:YES];
}

// 删除审批人
- (void)teaLeaveRecordFlowChartViewDeleteApprover:(ZYCTeaLeaveApplyUserModel *)m{
    [self.toUsers removeObject:m];
}

#pragma mark - ZYCTeaLeaveAddPhotoCellDelegate
- (void)teaLeaveBrowserWithIndex:(NSInteger)index PhotoCell:(ZYCTeaLeaveAddPhotoCell *)cell{
    NSMutableArray *browserDataArr = [NSMutableArray array];
    NSArray <ZYCTeaLeaveRecordFileModel *>*filesArray = cell.dataSource;
    [filesArray enumerateObjectsUsingBlock:^(ZYCTeaLeaveRecordFileModel * _Nonnull fileModel, NSUInteger idx, BOOL * _Nonnull stop) {
        YBIBImageData *data = [YBIBImageData new];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/zd-system-service%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],fileModel.filePath]];
        data.imageURL = url;
        [browserDataArr addObject:data];
    }];
    YBImageBrowser *browser = [YBImageBrowser new];
    browser.dataSourceArray = browserDataArr;
    browser.currentPage = index;
    [browser show];
}

#pragma mark - getters
- (ZYCTeaLeaveRecordDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ZYCTeaLeaveRecordDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80.0f)];
    }
    return _headerView;
}
- (ZYCTeaLeaveRecordFlowChartView *)flowChartView {
    if (!_flowChartView) {
        _flowChartView = [[ZYCTeaLeaveRecordFlowChartView alloc] init];
        _flowChartView.type = ZYCTeaLeaveFlowChartOther;
        _flowChartView.delegate = self;
    }
    return _flowChartView;
}


- (ZYCTeaLeaveRecordApproveBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[ZYCTeaLeaveRecordApproveBottomView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 49.0f, kScreenWidth, 49.0f)];
        _bottomView.delegate = self;
    }
    return _bottomView;
}
- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = @[@"所属部门:",@"所属岗位:",@"类型/时间:",@"请假事由",@"上传图片"];
    }
    return _dataSource;
}

- (NSMutableArray *)toUsers {
    if (!_toUsers) {
        _toUsers = [NSMutableArray arrayWithCapacity:0];
    }
    return _toUsers;
}

- (NSArray *)footerDataSource {
    if (!_footerDataSource) {
        _footerDataSource = [[NSArray alloc] init];
    }
    return _footerDataSource;
}

- (NSMutableArray *)approveArray {
    if (!_approveArray) {
        _approveArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _approveArray;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight - 49.0f) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = HEX_RGB(@"#FAFAFA");
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCTeaLeaveRecordDetailCell class] forCellReuseIdentifier:NSStringFromClass([ZYCTeaLeaveRecordDetailCell class])];
        [_tableView registerClass:[ZYCTeaLeaveOptionalCell class] forCellReuseIdentifier:NSStringFromClass([ZYCTeaLeaveOptionalCell class])];
        [_tableView registerClass:[ZYCTeaLeaveAddPhotoCell class] forCellReuseIdentifier:NSStringFromClass([ZYCTeaLeaveAddPhotoCell class])];
        [_tableView registerClass:[ZYCManageCourseTeachTimeCell class] forCellReuseIdentifier:NSStringFromClass([ZYCManageCourseTeachTimeCell class])];
        _tableView.showsVerticalScrollIndicator = NO;
    }
    return _tableView;
}

#pragma mark - 网络请求
- (void)loadTeaLeaveDetial{
    NSDictionary *params = @{
        @"teacherLeaveId":self.teacherLeaveId,
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_GetInfo requestService:RequestServiceActiviti parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                self.detailModel = [ZYCTeaLeaveRecordRootModel yy_modelWithDictionary:responseObject[@"body"]];
                self.detailModel.taskId = self.taskId;
                self.headerView.model = self.detailModel;
                [self getflowChart];
     
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

- (void)getflowChart{
    NSDictionary *params = @{
        @"teacherLeaveId":self.teacherLeaveId,
        @"taskId":self.taskId 
    };
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_EditHistory requestService:RequestServiceActiviti parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        [MrjSVProgressHUD dismiss];
        if (SUCCESS(responseObject[@"code"])) {
            NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCTeaLeaveFlowChartModel class] json:responseObject[@"body"]];
            for (ZYCTeaLeaveFlowChartModel *model in array) {
                if ([model.nodeType integerValue] == 3) {
                    
                    [model.applyUserList removeAllObjects];
                }
                model.isShow = YES;
                if ([model.nodeType  integerValue] == 3) { // 下一审批节点
                    for (ZYCTeaLeaveApplyUserModel *m in model.applyUserList) {
                        m.nodeType = model.nodeType;
                    }
                }
            }

            self.flowChartView.frame = CGRectMake(0, 0, kScreenWidth, array.count * 120 + 50.0f);
            ZYCTeaLeaveFlowChartModel *last = array.lastObject;
            self.nodeType = [last.nodeType integerValue];
            last.isShow = NO;
            self.footerDataSource = array;
            self.flowChartView.dataSource = array;
            [self.flowChartView reload];
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - ZYCTeaLeaveRecordApproveBottomViewDelegate
- (void)teaLeaveRecordApproveBottomViewClick:(ZYCTeaLeaveApproveBottomType)type{
    ZYCWeakSelf
    if (type == ZYCTeaLeaveApproveBottomTypeReject) {
        ZYCTeaLeaveApproveViewController *vc = [[ZYCTeaLeaveApproveViewController alloc] init];
        vc.popBlock = ^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
        vc.type = ZYCTeaLeaveApproveTypeReject;
        vc.toUsers = self.toUsers;
        vc.teacherLeaveId = self.teacherLeaveId;
        vc.taskId = self.taskId;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self passTeaLeave];
    }
}


// 请假通过
- (void)passTeaLeave{
    
    if (self.nodeType == 3) {
        if (self.toUsers.count == 0) {
            [MrjToast makeToast:@"请选择审批人" makeView:self.view];
            return;
        }
    }
    NSDictionary *params = @{
        @"businessKey":self.teacherLeaveId,
        @"taskId":self.taskId,
        @"status":@"1",
        @"toUsers":[self.toUsers componentsJoinedByString:@","],
    };
    
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_DoTask requestService:RequestServiceActiviti parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                [MrjToast makeToast:responseObject[@"body"] makeView:self.view];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
                
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}






/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
